using TMPro;
using UnityEngine;

public class UI_QuestPreview : MonoBehaviour
{
    [SerializeField] private TextMeshProUGUI questName;
    [SerializeField] private TextMeshProUGUI questDescription;
    [SerializeField] private TextMeshProUGUI questGoal;
    [SerializeField] private UI_QuestRewardSlot[] questRewardSlot;
    [SerializeField] private TextMeshProUGUI questAcceptBTN_Text;
    public QuestDataSO questDataSO { get; private set; }
    private PlayerQuestManager questManager;
    private UI_Quest questUI;

    public void SetupQuestPreview(QuestDataSO questDataSO)
    {
        questUI = transform.root.GetComponent<UI>().questUI;
        this.questDataSO = questDataSO;
        questManager = questUI.questManager;

        questName.text = questDataSO.questName;
        questDescription.text = questDataSO.description;
        questGoal.text = questDataSO.questGoal;

        for (int i = 0; i < questDataSO.rewardItems.Length; i++)
        {
            if (questDataSO.rewardItems == null || questDataSO.rewardItems[i] == null)
                continue;

            Inventory_Item rewardItem = new(questDataSO.rewardItems[i].itemData);
            rewardItem.stackSize = questDataSO.rewardItems[i].stackSize;

            questRewardSlot[i].gameObject.SetActive(true);
            questRewardSlot[i].UpdateItemSlot(rewardItem);
        }
        UpdateAcceptBTN();
    }

    public void InitQuestPreview(QuestDataSO questDataSO)
    {
        questName.text = questDataSO.questName;
        questDescription.text = questDataSO.description;
        questGoal.text = questDataSO.questGoal;

        EnableQuestRewardSlot(questDataSO);

        SetupQuestPreview(questDataSO);
    }

    public void AcceptQuest()
    {
        if (!questManager.IsAcceptedQuest(questDataSO) && questManager.CanAcceptQuest())
        {
            questManager.AcceptQuest(questDataSO);
            questUI.UpdateQuestList();
        }
        else
        {
            questManager.CancelQuest(questDataSO);
            questUI.UpdateQuestList();
        }

        UpdateAcceptBTN();
    }
    public void UpdateAcceptBTN()
    {
        if (questManager.IsAcceptedQuest(questDataSO))
        {
            questAcceptBTN_Text.text = "Cancel";
            questAcceptBTN_Text.color = Color.red;
        }
        else
        { 
            questAcceptBTN_Text.text = "Accept";
            questAcceptBTN_Text.color = Color.white;
        }
    }
    private void EnableQuestRewardSlot(QuestDataSO questDataSO)
    {
        foreach (var slot in questRewardSlot)
            slot.gameObject.SetActive(false);

        for (int i = 0; i < questDataSO.rewardItems.Length; i++)
        {
            Inventory_Item itemToInit = new(questDataSO.rewardItems[i].itemData);

            itemToInit.stackSize = questDataSO.rewardItems[i].stackSize;

            questRewardSlot[i].UpdateItemSlot(itemToInit);
        }
    }
}
